package com.yjzx.bean;

import com.yjzx.interfaces.CommonClasses;
import com.yjzx.util.CollectionUtil;
import javassist.*;

import java.util.List;

/**
 * @author yjzx
 * @date 2023/10/26
 * @description InterfaceInfo
 */
public class UpdateInterface extends JavassistInfo {
    private String interfaceName;
    private List<UpdateMethod> methods;

    public String getInterfaceName() {
        return interfaceName;
    }

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }

    public List<UpdateMethod> getMethods() {
        return methods;
    }

    public void setMethods(List<UpdateMethod> methods) {
        this.methods = methods;
    }

    public UpdateInterface() {
    }

    public UpdateInterface(String interfaceName) {
        this.interfaceName = interfaceName;
    }

    public CtClass toInterface(ClassPool pool, CtClass ctClass) {
        this.check();
        CtClass ctClass1;
        try {
            ctClass1 = CommonClasses.getCtClass(pool, interfaceName);
            if (CollectionUtil.isNotEmpty(methods)) {
                for (UpdateMethod method : methods) {
                    method.addAnnotate(new UpdateAnnotate("java.lang.Override",null));
                    CtMethod ctMethod = method.toMethod(pool, ctClass1);
                    String descriptor = ctMethod.getMethodInfo2().getDescriptor();
                    if (ctClass1.getMethod(ctMethod.getName(), descriptor)!=null) {
                        ctClass1.addMethod(ctMethod);
                    }else {
                        throw new RuntimeException("接口"+ctClass1.getName()+"不存在方法："+ctMethod.getName()+descriptor);
                    }
                }

            }
            return ctClass1;
        } catch (NotFoundException | CannotCompileException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void check() {
        this.checkParam(this.interfaceName);
    }
}
